package logic

import (
	"sync"
	"yundian/internel/app/models/membermodel"
	"yundian/internel/app/models/users"
	"yundian/internel/pkg/dingo/global"
)

type WifiUserLogic struct {
}

func NewWifiUserLogic() *WifiUserLogic {
	return &WifiUserLogic{}
}

type InviteRecordWithConfig struct {
	ParentId int    `gorm:"column:parent_id" json:"parentId"`
	UserId   int    `gorm:"column:user_id" json:"userId"`
	Phone    string `gorm:"column:phone" json:"phone"`
	BelowProportion int   `gorm:"column:below_proportion" json:"belowProportion"`
	IsAdmin         uint8 `gorm:"column:is_admin" json:"isAdmin"`
}

// WIFI 用户更新
func (logic *WifiUserLogic) UpdateUserToWifiUser() {
	// 查询用户列表
	var lists []*users.UserModel

	sql := "SELECT * FROM users"
	//sql := "SELECT * FROM users WHERE parent_id IN (SELECT id FROM users WHERE is_steward = 3)"
	//sql := "SELECT * FROM users WHERE parent_id IN (SELECT id FROM users WHERE parent_id IN (SELECT id FROM users WHERE is_steward = 3))"
	global.Orm.Debug().Raw(sql).Find(&lists)

	maxGoroutine := 6 // 开启协程的大小
	var pool chan struct{}
	pool = make(chan struct{}, maxGoroutine) // 协程池
	var wg sync.WaitGroup
	for _, lst := range lists {
		wg.Add(1)
		pool <- struct{}{}
		go func(item *users.UserModel) {
			defer wg.Done()
			defer func() {
				<- pool
			}()
			// 获取该用户的会员信息
			memberInfo := membermodel.New()
			msql := "select * from members where phone = ? and app_id = ? limit 1"
			global.Orm.Debug().Raw(msql, item.Phone, "wxa2d02c6a1e8ffb24").Find(&memberInfo)

			// 获取邀请的会员信息
			//recordInfo := &InviteRecordWithConfig{}
			//usql := "SELECT uir.parent_id,uir.user_id,uir.phone,uic.is_admin,uic.below_proportion FROM users_invite_record uir " +
			//	"LEFT JOIN users_invite_config uic ON uir.invite_id = uic.id WHERE uir.user_id = ?"
			//global.Orm.Debug().Raw(usql, item.ID).Find(&recordInfo)

			// 判断该用户是否已经在关联表中存在
			var c int64
			wsql := "select count(1) from wifi_user where user_id = ?"
			global.Orm.Raw(wsql, item.ID).Count(&c)

			if c <= 0 {
				m := &users.WifiUser{}
				m.IsAdmin = item.IsAdmin
				m.ProfitProportion = item.ProfitProportion
				m.UserId = item.ID
				m.MemberId = memberInfo.ID
				m.ParentId = item.ParentID
				// 新增
				global.Orm.Table("wifi_user").Create(&m)
			} else {
				m := &users.WifiUser{}
				m.IsAdmin = item.IsAdmin
				m.ProfitProportion = item.ProfitProportion
				m.UserId = item.ID
				m.MemberId = memberInfo.ID
				m.ParentId = item.ParentID
				global.Orm.Table("wifi_user").Model(m).
					Where("user_id = ?", item.ID).
					Where("member_id = ?", memberInfo.ID).Updates(&m)
			}
		}(lst)
	}
}
